import { Button, Form, Input, message } from "antd"
import { UserOutlined, LockOutlined } from "@ant-design/icons"
import { AppName, FormContainer, LoginContainer } from "./style"
import { useHistory } from "react-router-dom"
import { http } from "@/utils/http"
import { userType } from "@/types"
import { connect, ConnectedProps } from "react-redux"
import { setUserInfo } from "@/store/actions/user"

type Props = ConnectedProps<typeof connector>

const Login: React.FC<Props> = (props) => {
  const { setUserInfo } = props

  const history = useHistory()

  /**
   * 点击登录
   * @param userInfo 用户信息
   */
  const login = async (userInfo: { username: string; password: string }) => {
    try {
      const { data: res } = await http.post(`/login?userName=${userInfo.username}&passWord=${userInfo.password}`)

      if (res.data === "密码错误！") return message.error("密码错误")
      if (res.data === "账号不存在！") return message.error("账号不存在")
      if (res.data === "该用户已被封禁，请联系上级管理员！") return message.error("该用户已被封禁，请联系上级管理员！")

      sessionStorage.setItem("token", res.data.token)

      // userInfo存储到store中
      setUserInfo(res.data.user as userType)

      message.success("登录成功")
      history.replace("/home/data-panel")
    } catch {
      message.error("服务器异常")
    }
  }

  return (
    <LoginContainer>
      <FormContainer>
        <AppName>智慧帮扶后台管理系统</AppName>

        <Form autoComplete="off" onFinish={login} style={{ width: "100%", flex: 1, display: "flex", flexDirection: "column" }}>
          <Form.Item name="username" rules={[{ required: true, message: "Please input your username!" }]}>
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: "Please input your password!" }]}>
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>
          <Form.Item style={{ marginTop: "auto" }}>
            <Button type="primary" htmlType="submit" size="large" block>
              立即登录
            </Button>
          </Form.Item>
        </Form>
      </FormContainer>
    </LoginContainer>
  )
}

const connector = connect(() => ({}), {
  setUserInfo,
})

export default connector(Login)
